

//
//  Teacher.m
//  runtime
//
//  Created by YYY on 2018/1/11.
//  Copyright © 2018年 YYY. All rights reserved.
//

#import "Teacher.h"
#import <objc/runtime.h>

@implementation Teacher

//归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int count = 0;
    Ivar *list = class_copyIvarList([self class], &count);
    //遍历所有的属性
    for (unsigned int i = 0; i < count; i++)
    {
        //取出i位置对应的成员变量
        Ivar ivar = list[i];
        //查看成员变量
        const char *name = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:name];
        //归档
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    free(list);
}

//解归档
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        unsigned int count = 0;
        Ivar *list = class_copyIvarList([self class], &count);
        //遍历所有的属性
        for (unsigned int i = 0; i < count; i++)
        {
            //取出i位置对应的成员变量
            Ivar ivar = list[i];
            //查看成员变量
            const char *name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];
            //归档
            id value = [aDecoder decodeObjectForKey:key];
            //设置到成员变量身上
            [self setValue:value forKey:key];
        }
        free(list);
    }
    return self;
}
@end
